package com.demo.service.riot;

import com.demo.mapper.riot.CleanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Instant;
import java.util.List;

@Service
@Slf4j
public class CleanService {

    private final CleanMapper cleanMapper;
    private static final int BATCH_SIZE = 1000;

    public CleanService(CleanMapper cleanMapper) {
        this.cleanMapper = cleanMapper;
    }

    @Transactional
    public int cleanupOutdatedMatches(int retentionDays) {
        LocalDateTime threshold = LocalDateTime.now().minusDays(retentionDays);
        Instant start = Instant.now();
        int totalDeleted = 0;

        while (true) {
            List<String> outdatedMatches = cleanMapper.selectOutdatedMatches(threshold, BATCH_SIZE);
            if (outdatedMatches.isEmpty()) break;

            cleanMapper.deleteMatchParticipants(outdatedMatches);
            cleanMapper.deleteMatchTeams(outdatedMatches);
            cleanMapper.deletePlayerMatches(outdatedMatches);
            int deleted = cleanMapper.deleteMatches(outdatedMatches);
            totalDeleted += deleted;

            log.info("Deleted {} matches in current batch", deleted);
            if (deleted < BATCH_SIZE) break;
        }

        long duration = Duration.between(start, Instant.now()).getSeconds();
        cleanMapper.logCleanup("match_cleanup", totalDeleted, duration);
        return totalDeleted;
    }

    @Transactional
    public int cleanupOutdatedRankInfo(int retentionDays) {
        LocalDateTime threshold = LocalDateTime.now().minusDays(retentionDays);
        Instant start = Instant.now();

        int deleted = cleanMapper.deleteOutdatedRankInfo(threshold);
        long duration = Duration.between(start, Instant.now()).getSeconds();

        cleanMapper.logCleanup("rank_cleanup", deleted, duration);
        return deleted;
    }

    @Transactional
    public int cleanupInactiveSummoners(int retentionDays) {
        LocalDateTime threshold = LocalDateTime.now().minusDays(retentionDays);
        Instant start = Instant.now();
        int totalDeleted = 0;

        List<String> inactiveSummoners = cleanMapper.selectInactiveSummoners(threshold);
        if (!inactiveSummoners.isEmpty()) {
            cleanMapper.deleteSummonerInfo(inactiveSummoners);
            totalDeleted = cleanMapper.deleteSummoners(inactiveSummoners);
        }

        long duration = Duration.between(start, Instant.now()).getSeconds();
        cleanMapper.logCleanup("summoner_cleanup", totalDeleted, duration);
        return totalDeleted;
    }
}